package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/Company", "/company", "/CompanyServlet", "/companyServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class CompanyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public CompanyServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<CompanyModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("companyNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			CompanyModel query = new CompanyModel();
			String id = request.getParameter("id");
			int role = MiscUtil.getIntUrlParam(request, "role");
			query.setId(Integer.parseInt(id));

			GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());

			CompanyModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("company", obj);
				getServletContext().getRequestDispatcher("/companyEdit.jsp?role="+role).forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			CompanyModel query = new CompanyModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());

			CompanyModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("company", obj);
				response.sendRedirect("companyView.jsp");

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			CompanyModel obj = new CompanyModel();

			// SET NAME here

			GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());
			int res = 0;

			try {
				String strName = request.getParameter("short_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setShortName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("company", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			CompanyModel query = new CompanyModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("companyList.jsp");
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");
		int role = MiscUtil.getIntUrlParam(request, "role");

		if (mode.equalsIgnoreCase("insert")) {

			CompanyModel obj = new CompanyModel();
			String code = request.getParameter("code");
			obj.setCode(code);
if(role!=2)
{
String is_competitor = request.getParameter("is_competitor");
			obj.setIsCompetitor(is_competitor!=null);
}
else
{
	obj.setIsCompetitor(true);
}
//					|| is_competitor.equalsIgnoreCase("1"));
//
//String abb_name = request.getParameter("abb_name");
//			obj.setAbbName(abb_name);

String short_name = request.getParameter("short_name");
			obj.setShortName(short_name);

String full_name = request.getParameter("full_name");
			obj.setFullName(full_name);

String foreign_name = request.getParameter("foreign_name");
			obj.setForeignName(foreign_name);

String address = request.getParameter("address");
			obj.setAddress(address);

String telephone = request.getParameter("telephone");
			obj.setTelephone(telephone);

String fax = request.getParameter("fax");
			obj.setFax(fax);

String tax_code = request.getParameter("tax_code");
			obj.setTaxCode(tax_code);

String remark = request.getParameter("remark");
			obj.setRemark(remark);

String contact_person_1 = request.getParameter("contact_person_1");
			obj.setContactPerson1(contact_person_1);

String contact_phone_1 = request.getParameter("contact_phone_1");
			obj.setContactPhone1(contact_phone_1);

String contact_mobile_1 = request.getParameter("contact_mobile_1");
			obj.setContactMobile1(contact_mobile_1);

String contact_email_1 = request.getParameter("contact_email_1");
			obj.setContactEmail1(contact_email_1);

String contact_person_2 = request.getParameter("contact_person_2");
			obj.setContactPerson2(contact_person_2);

String contact_phone_2 = request.getParameter("contact_phone_2");
			obj.setContactPhone2(contact_phone_2);

String contact_mobile_2 = request.getParameter("contact_mobile_2");
			obj.setContactMobile2(contact_mobile_2);

String contact_email_2 = request.getParameter("contact_email_2");
			obj.setContactEmail2(contact_email_2);

String id_place = request.getParameter("id_place");
            if (id_place != null && !id_place.isEmpty()) {
			    obj.setIdPlace(Integer.parseInt(id_place));
            }

//String map_path = request.getParameter("map_path");
//			obj.setMapPath(map_path);

String description = request.getParameter("description");
			obj.setDescription(description);

//String status = request.getParameter("status");
//            if (status != null && !status.isEmpty()) {
//			    obj.setStatus(Integer.parseInt(status));
//            }
//
//String is_draft = request.getParameter("is_draft");
//			obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//					|| is_draft.equalsIgnoreCase("1"));
//
//String notification = request.getParameter("notification");
//            if (notification != null && !notification.isEmpty()) {
//			    obj.setNotification(Integer.parseInt(notification));
//            }
			if(role!=4)
			{
				String is_provider = request.getParameter("is_provider");
				obj.setIsProvider(is_provider!=null);
			}
			else
				obj.setIsProvider(true);
//					|| is_provider.equalsIgnoreCase("1"));
			if(role!=1)
			{
				String is_client = request.getParameter("is_client");
				obj.setIsClient(is_client!=null);
			}
			else
				obj.setIsClient(true);
			
//					|| is_client.equalsIgnoreCase("1"));
			if(role!=3)
			{
				String is_broker = request.getParameter("is_broker");
				obj.setIsBroker(is_broker!=null);
			}
			else
				obj.setIsBroker(true);
//					|| is_broker.equalsIgnoreCase("1"));

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, refresh cache and redirect to somewhere
					response.sendRedirect("companyNew.jsp?role="+role);
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("company", obj);
				getServletContext().getRequestDispatcher("/companyInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			CompanyModel query = new CompanyModel();
			String id = request.getParameter("id");
			
			query.setId(Integer.parseInt(id));

			GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());

			CompanyModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				
				String code = request.getParameter("code");
				obj.setCode(code);
				if(role!=2)
				{
					String is_competitor = request.getParameter("is_competitor");
					obj.setIsCompetitor(is_competitor != null);
					obj.setIsCompetitorSet(true);
				}
	//
	//String abb_name = request.getParameter("abb_name");
//				obj.setAbbName(abb_name);

	String short_name = request.getParameter("short_name");
				obj.setShortName(short_name);

	String full_name = request.getParameter("full_name");
				obj.setFullName(full_name);

	String foreign_name = request.getParameter("foreign_name");
				obj.setForeignName(foreign_name);

	String address = request.getParameter("address");
				obj.setAddress(address);

	String telephone = request.getParameter("telephone");
				obj.setTelephone(telephone);

	String fax = request.getParameter("fax");
				obj.setFax(fax);

	String tax_code = request.getParameter("tax_code");
				obj.setTaxCode(tax_code);

	String remark = request.getParameter("remark");
				obj.setRemark(remark);

	String contact_person_1 = request.getParameter("contact_person_1");
				obj.setContactPerson1(contact_person_1);

	String contact_phone_1 = request.getParameter("contact_phone_1");
				obj.setContactPhone1(contact_phone_1);

	String contact_mobile_1 = request.getParameter("contact_mobile_1");
				obj.setContactMobile1(contact_mobile_1);

	String contact_email_1 = request.getParameter("contact_email_1");
				obj.setContactEmail1(contact_email_1);

	String contact_person_2 = request.getParameter("contact_person_2");
				obj.setContactPerson2(contact_person_2);

	String contact_phone_2 = request.getParameter("contact_phone_2");
				obj.setContactPhone2(contact_phone_2);

	String contact_mobile_2 = request.getParameter("contact_mobile_2");
				obj.setContactMobile2(contact_mobile_2);

	String contact_email_2 = request.getParameter("contact_email_2");
				obj.setContactEmail2(contact_email_2);

	String id_place = request.getParameter("id_place");
	            if (id_place != null && !id_place.isEmpty()) {
				    obj.setIdPlace(Integer.parseInt(id_place));
	            }

	//String map_path = request.getParameter("map_path");
//				obj.setMapPath(map_path);

	String description = request.getParameter("description");
				obj.setDescription(description);

	//String status = request.getParameter("status");
//	            if (status != null && !status.isEmpty()) {
//				    obj.setStatus(Integer.parseInt(status));
//	            }
	//
	//String is_draft = request.getParameter("is_draft");
//				obj.setIsDraft(is_draft.equalsIgnoreCase("true")
//						|| is_draft.equalsIgnoreCase("1"));
	//
	//String notification = request.getParameter("notification");
//	            if (notification != null && !notification.isEmpty()) {
//				    obj.setNotification(Integer.parseInt(notification));
//	            }
				if(role!=4)
				{
					String is_provider = request.getParameter("is_provider");
					obj.setIsProvider(is_provider != null);
					obj.setIsProviderSet(true);
				}
				
				if(role!=1)
				{
					String is_client = request.getParameter("is_client");
					obj.setIsClient(is_client != null);
					obj.setIsClientSet(true);
				}
				
				if(role!=3)
				{
					String is_broker = request.getParameter("is_broker");
					obj.setIsBroker(is_broker != null);
					obj.setIsBrokerSet(true);
				}
				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("companyList.jsp?role="+role);
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("company", obj);
					getServletContext().getRequestDispatcher("/companyList.jsp?role="+role).forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			CompanyModel obj = new CompanyModel();

			// SET NAME here

			GenericDal<CompanyModel, CompanyModelExt> dal = new GenericDal<CompanyModel, CompanyModelExt>(new CompanyModel());
			int res = 0;

			try {
				String strName = request.getParameter("short_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setShortName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("company", "" + res);
					out.println(resultXML);
				}
				else
				{
					//TODO: respone something
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}